package com.simon.app.october.modules.sys.service.impl;

import com.simon.app.october.common.utils.Constant;
import com.simon.app.october.modules.sys.dao.SysMenuDao;
import com.simon.app.october.modules.sys.dao.SysUserDao;
import com.simon.app.october.modules.sys.dao.SysUserTokenDao;
import com.simon.app.october.modules.sys.entity.SysMenuEntity;
import com.simon.app.october.modules.sys.entity.SysUserTokenEntity;
import com.simon.app.october.modules.sys.service.ShiroService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements ShiroService {

    @Autowired
    private SysUserTokenDao tokenDao;

    @Autowired
    private SysMenuDao menuDao;

    @Autowired
    private SysUserDao userDao;

    @Override
    public SysUserTokenEntity findByToken(String token) {
        return tokenDao.findByToken(token);
    }

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;
        // 如果是管理员则有全部权限
        if (userId == Constant.SUPER_ADMIN) {
            // 先获取所有菜单实体
            List<SysMenuEntity> menuList = menuDao.getList();
            permsList = new ArrayList<>(menuList.size());
            for (SysMenuEntity menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = userDao.getUserPermissions(userId);
        }

        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            if (StringUtils.isBlank(perms)) {
                continue;
            }

            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }

        return permsSet;
    }
}
